package com.zhxy.controller;

import com.wf.captcha.utils.CaptchaUtil;
import com.zhxy.param.LoginForm;
import com.zhxy.pojo.Admin;
import com.zhxy.service.AdminService;
import com.zhxy.utils.JWTUtils;
import com.zhxy.utils.RedisUtils;
import com.zhxy.utils.Result;
import com.zhxy.utils.StatusCode;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RequestMapping("/system")
@RestController
public class SystemController {
    @Autowired
    private AdminService adminService;
    @Autowired
   private JWTUtils jwtUtils;
    @Autowired
   private RedisUtils redisUtils;
    @Autowired
    private RedisTemplate redisTemplate;

    @PostMapping("/login")
    @ApiOperation(value = "系统登录")
    @ApiImplicitParam(required = true,value = "实体类",name = "loginForm")
    public Result login(@RequestBody LoginForm loginForm) throws Exception{
     //1.验证码是否正确
        Object code = redisTemplate.opsForValue().get("code");

        if(code==null||!loginForm.getVerifiCode().equals(code.toString()))
            throw new Exception("验证码错误");
        System.out.println("验证码正确");
        redisTemplate.delete("code");//从redis中删除数据
        switch (loginForm.getUserType()) {
            case 1:
                //管理员
                Admin admin = adminService.login(loginForm.getUsername(), loginForm.getPassword());
                //使用jwt生成一个token
                 String token = jwtUtils.createJWT(admin.getId() + "", admin.getName(), "admin");
                 Map<String,String> map=new HashMap<>();
                 map.put("token",token);
               // return new Result(StatusCode.SUCCESS,"操作成功",map);
                return  Result.ok(map);

            case 2:
                //学生
            case 3:
                //老师
        }


        return null;
    }

    @GetMapping("/captcha")
    public void createCaptcha(HttpServletRequest request, HttpServletResponse response, HttpSession session) throws Exception{
        CaptchaUtil.out(request,response);//生成了4个字母的验证码，保存到session中
        //获取验证码
        String captcha = (String)session.getAttribute("captcha");
        System.out.println("验证码为:"+captcha);

        //保存到redis中，设置5分钟有效，字符串
        redisTemplate.opsForValue().set("code",captcha,5, TimeUnit.MINUTES);
        redisUtils.set("code",captcha,5*60);
    }


}
